package com.kj.xuyuan.home;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kj.xuyuan.R;
import com.kj.xuyuan.adapter.DynamicAdapter;
import com.kj.xuyuan.adapter.TopicListAdapter;
import com.kj.xuyuan.base.BaseFragment;
import com.kj.xuyuan.base.BaseModel;
import com.kj.xuyuan.base.Constants;
import com.kj.xuyuan.http.JsonCallback;
import com.kj.xuyuan.http.OkGoUtil;
import com.kj.xuyuan.http.UrlConstants;
import com.kj.xuyuan.model.DynamicBean;
import com.kj.xuyuan.model.FriendBean;
import com.kj.xuyuan.model.VipListBean;
import com.kj.xuyuan.util.LogUtils;
import com.kj.xuyuan.util.PhotoViewActivity;
import com.kj.xuyuan.util.SPUtils;
import com.kj.xuyuan.util.ToastUtil;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

public class DynamicFragment extends BaseFragment {

    @BindView(R.id.rv_top)
    RecyclerView rvTop;
    @BindView(R.id.rv_dynamic)
    RecyclerView rvDynamic;
    @BindView(R.id.iv_publish_dynamic)
    ImageView ivPublishDynamic;
    @BindView(R.id.sml_dynamic)
    SmartRefreshLayout smlDynamic;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;

    private int type; //1动态  2熟人  3个人主页使用，需隐藏顶部列表和item的喜欢按钮

    //话题数据和适配器
    private List<VipListBean> topicList;
    private TopicListAdapter topicAdapter;
    private int page = 1;

    //熟人数据和适配器
    private List<FriendBean> friendList;

    //动态数据和适配器
    private List<DynamicBean> dynamicList;
    private DynamicAdapter dynamicAdapter;
    private String userId;

    public static DynamicFragment newInstance(int type,String userId) {
        Bundle arguments = new Bundle();
        arguments.putInt("type", type);
        arguments.putString("userId", userId);
        DynamicFragment fl = new DynamicFragment();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.layout_fragment_dynamic;
    }

    @Override
    protected void initView() {
        type = getArguments().getInt("type");
        if(type == 1){//动态
            initTopicRecyclerView();
            getTopicData();
        }else if(type == 2){
            initFriendRecyclerView();
            getFriendData();
        }else if(type == 3){
            userId = getArguments().getString("userId");
            rvTop.setVisibility(View.GONE);
        }

        initDynamicRecyclerView();
        getDynamic();
    }

    private void getFriendData() {
        Map map = new HashMap();
        map.put("page", "1");

        OkGoUtil.postRequest(getContext(), UrlConstants.FRIEND_LIST, map, new JsonCallback<BaseModel<List<VipListBean>>>() {
            @Override
            public void onSuccess(Response<BaseModel<List<VipListBean>>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){

                    }
                    ToastUtil.showToast(getContext(),response.body().getMsg());
                }
            }

            @Override
            public void onError(Response<BaseModel<List<VipListBean>>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
            }
        });
    }

    private void initFriendRecyclerView() {

    }

    private void initDynamicRecyclerView() {
        dynamicList = new ArrayList<>();
        dynamicAdapter = new DynamicAdapter();
        rvDynamic.setLayoutManager(new LinearLayoutManager(getContext()));
        rvDynamic.setAdapter(dynamicAdapter);
        dynamicAdapter.setNewData(dynamicList);

        smlDynamic.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getDynamic();
            }
        });

        smlDynamic.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page ++;
                getDynamic();
            }
        });

        dynamicAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                DynamicDetailsActivity.actionStar(getContext(),dynamicList.get(position).getId());
            }
        });

        dynamicAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    case R.id.tv_like_or_chat:
                        //是否点过喜欢 0否 1是
                        if(dynamicList.get(position).getIs_like_message() == 0){//没点过，走喜欢逻辑
                            like(position);
                        }else{//点过，跳转聊天页

                        }
                        break;
                    case R.id.tv_like:
                        dynamicLike(position);
                        break;
                    case R.id.tv_comment:
                        DynamicDetailsActivity.actionStar(getContext(),dynamicList.get(position).getId());
                        break;
                    case R.id.tv_tag:
                        DynamicTopicDetailsActivity.actionStar(getContext(),dynamicList.get(position).getTopic_id(),
                                dynamicList.get(position).getTopic().getTitle(),
                                dynamicList.get(position).getTopic().getContent(),
                                dynamicList.get(position).getTopic().getCover_image());
                        break;
                }
            }
        });

        dynamicAdapter.setImageClickListener(new DynamicAdapter.ImageClickListener() {
            @Override
            public void imageClick(int position1, int position2) {
                LogUtils.e(TAG,"54654563");
                PhotoViewActivity.actionStar(getContext(),dynamicList.get(position1).getImage(),position2);
            }
        });
    }

    private void dynamicLike(int position) {
        showDialog();
        Map map = new HashMap();
        map.put("type",dynamicList.get(position).getIs_like() == 0 ? "1" : "0");
        map.put("topic_comment_id",dynamicList.get(position).getId()+"");
        OkGoUtil.postRequest(getContext(), UrlConstants.DYNAMIC_LIKE, map, new JsonCallback<BaseModel<?>>() {
            @Override
            public void onSuccess(Response<BaseModel<?>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        dynamicList.get(position).setIs_like(dynamicList.get(position).getIs_like() == 0 ? 1 : 0);
                        dynamicAdapter.notifyDataSetChanged();
                    }
                    ToastUtil.showToast(getContext(),response.body().getMsg());
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<BaseModel<?>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
                dismissDialog();
            }
        });
    }

    private void like(int position) {
        showDialog();
        Map map = new HashMap();
        map.put("for_user_id",dynamicList.get(position).getUser().getId()+"");
        OkGoUtil.postRequest(getContext(), UrlConstants.LIKE, map, new JsonCallback<BaseModel<?>>() {
            @Override
            public void onSuccess(Response<BaseModel<?>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        dynamicList.get(position).setIs_like_message(dynamicList.get(position).getIs_like_message() == 0 ? 1 : 0);
                        dynamicAdapter.notifyDataSetChanged();
                    }
                    ToastUtil.showToast(getContext(),response.body().getMsg());
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<BaseModel<?>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
                dismissDialog();
            }
        });
    }


    private void getDynamic() {
        Map map = new HashMap();
        map.put("page", page+"");
        if(type == 2){
            map.put("is_friend","1");
        }
        if(type == 3){
            map.put("user_id",userId);
        }
        OkGoUtil.postRequest(getContext(), UrlConstants.DYNAMIC_LIST, map, new JsonCallback<BaseModel<List<DynamicBean>>>() {
            @Override
            public void onSuccess(Response<BaseModel<List<DynamicBean>>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        if(page == 1){
                            dynamicList.clear();
                        }
                        dynamicList.addAll(response.body().getData());
                        dynamicAdapter.notifyDataSetChanged();

                        llNoData.setVisibility(dynamicList.size() == 0 ? View.VISIBLE : View.GONE);
                        rvDynamic.setVisibility(dynamicList.size() == 0 ? View.GONE : View.VISIBLE);
                    }else{
                        ToastUtil.showToast(getContext(),response.body().getMsg());
                    }
                }
                smlDynamic.finishRefresh();
                smlDynamic.finishLoadMore();
            }

            @Override
            public void onError(Response<BaseModel<List<DynamicBean>>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
                smlDynamic.finishRefresh();
                smlDynamic.finishLoadMore();
            }
        });
    }

    private void getTopicData() {
        Map map = new HashMap();
        map.put("page", "1");

        OkGoUtil.postRequest(getContext(), UrlConstants.TOPIC, map, new JsonCallback<BaseModel<List<VipListBean>>>() {
            @Override
            public void onSuccess(Response<BaseModel<List<VipListBean>>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        topicList.clear();
                        topicList.addAll(response.body().getData());
                        topicAdapter.notifyDataSetChanged();
                    }
                    ToastUtil.showToast(getContext(),response.body().getMsg());
                }
            }

            @Override
            public void onError(Response<BaseModel<List<VipListBean>>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
            }
        });
    }

    private void initTopicRecyclerView() {
        topicList = new ArrayList<>();
        topicAdapter = new TopicListAdapter();
        rvTop.setLayoutManager(new LinearLayoutManager(getContext(),RecyclerView.HORIZONTAL,false));
        rvTop.setAdapter(topicAdapter);
        topicAdapter.setNewData(topicList);

        topicAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                DynamicTopicDetailsActivity.actionStar(getContext(),topicList.get(position).getId(),
                        topicList.get(position).getTitle(),
                        topicList.get(position).getContent(),
                        topicList.get(position).getCover_image());
            }
        });
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.iv_publish_dynamic})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_publish_dynamic:
                PublishDynamicActivity.actionStar(getContext(),-1,"");
                break;
        }
    }
}
